const { verifyToken } = require('../utils/utils')
const whiteList = /\/(web|login|register|sqliteweb|clear\/all)/ // 免token校验白名单

/**
 * token校验,用token换userId
 * @param {*} ctx 
 * @param {*} next 
 */
module.exports = async (ctx, next) => {
  let needToken = !whiteList.test(ctx.request.url) // 是否需要token校验
  if (needToken) {
    let token = ctx.query.token || ctx.request.body.token || ''
    if (token) {
      try {
        const valid = await verifyToken(token)
        switch (ctx.request.method) {
          case 'GET':
            ctx.query.userId = valid.data.userId
            break
          case 'POST':
            ctx.request.body.userId = valid.data.userId
            break
        }
        await next()
      } catch (err) {
        ctx.body = { code: 201, data: null, message: 'token失效或者无效token' }
      }
    } else {
      ctx.body = { code: 201, data: null, message: '缺少token参数' }
    }
  } else { // 验证token
    await next()
  }
}
